<template>
  <div class="page">
    <img class="sharebg" src="../../../static/images/sharebg.png">
    <div class="sharecon">
    <!--  <div class="sharecard" ref="share">
        <a class="close" href="#">×</a>
        <div class="weui-flex share_user">
          <img src="../../../static/images/p03.jpg">
          <div class="weui-flex__item">
            <div>王二</div>
            <div>我发起了一个很实惠的拼团还差1个人，安利</div>
          </div>
        </div>
        <img class="share_goods" mode="widthFix" src="../../../static/images/p02.jpg">
        <div class="weui-flex">
          <div class="weui-flex__item">
            <div class="share_title">精油养生油压精油养生油压套餐</div>
            <div class="share_group">
              <span>2人团</span>
              已团1件
            </div>
            <div class="share_pirce">
              <span class="red">￥0.01</span>
              拼团省199.09元
            </div>
          </div>
          <div class="share_store">
            <img mode="widthFix" src="../../../static/images/code.png">
          </div>
        </div>
      </div> -->
      <canvas style="width: 286px;height: 415px;background:#fff;" canvas-id="shareFrends"></canvas>
      <div class="share_tips" @click="canvasToImage()">点击保存图片</div>


    </div>
  </div>
</template>

<script>
  // import html2canvas from "html2canvas"

const Promise = require('es6-promise').Promise
export default {
  data () {
    return {
      openid:"",
      phone:"",
      userInfo:{},
      data:{},
      codeImg:"",
      url:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565521339343&di=58b7c4fd2f9ecc5d6fc62df8b209cfad&imgtype=0&src=http%3A%2F%2Fpic26.nipic.com%2F20121221%2F9252150_142515375000_2.jpg"
    }
  },
  onShow(){
    let that=this;
    let data=wx.getStorageSync('payShow')&&JSON.parse(wx.getStorageSync('payShow'))
    this.data=data[0]
    wx.login({
       success(res) {
         console.log(res)
         that.openid=res.code
         that.userInfo =wx.getStorageSync('userInfo')&&JSON.parse(wx.getStorageSync('userInfo'))
         that.phone=that.userInfo.mobileNo;
         that.getCodeImg().then((data)=>{
           console.log(data)
         })
         that.createdCode()
       },
     })


    // console.log(html2canvas)
  },
  methods: {

    getCodeImg(){
      let that=this;
      return new Promise((resolve,reject)=>{
        this.$http.request({
          method: "post",
          url: "/v1.0/appletOperat/getWxCode",
          body:{
             "appid":"wxc6c9bdac9d6a7456",
             "phone":this.phone,
             "pageNo":"1",
             "pageSize":"10",
             "path":"pages/share/main",
             "openid":this.openid
            }
        }).then((data)=>{
          if(data.code==0){
           this.codeImg=data.result
            // wx.downloadFile({
            //    url: that.codeImg,
            //    success:(res)=>{
            //      return resolve(res)
            //    }
            // })
          }
        })
      })

    },
       drawImage1 (ctx) {
                //创建img元素
                let img = new Image();
                //保证img元素绘制完成
                img.onload = function () {
                    ctx.drawImage(img, 0, 0);
                };
                img.src = this.url;
            },

    //开始绘图
    createdCode() {
      let that=this;
       const ctx = wx.createCanvasContext('shareFrends');    //绘图上下文
        // 绘制logo

        // this. drawImage1 (ctx)

//         // canvas 背景颜色设置不成功，只好用白色背景图

//         //绘制logo
            ctx.save()
           // wx.downloadFile({
           //   url:that.url,
             // success:(res)=>{
             //   let url=res.tempFilePath
                  console.log(that.userInfo.avatar)
                  // wx.downloadFile({
                  //   url:that.userInfo.avatar,
                  //   success(headerImg){
                  //     console.log(headerImg)


                         ctx.fillStyle="#FFFFFF";
                          ctx.fillRect(0,0,286,415);
//                       ctx.beginPath();
//
//                         ctx.arc(35, 35, 25, 0, Math.PI * 2, false);
//                         ctx.closePath();
//                          ctx.clip();
                       ctx.drawImage(that.userInfo.avatar, 10, 10, 51, 51);

                         ctx.restore();

                         ctx.setFontSize(12);
                          ctx.setFillStyle('#333333')
                          let username=that.userInfo.userName
                          ctx.fillText(username, 70,25);
                           that.wordsWrap(ctx,'我发起了一个很实惠的拼团还差1个人',215,215, 70, 45,12)
                            // ctx.fillText('我发起了一个很实惠的拼团还差1个人，安利', 65, 55);
                            // ctx.drawImage(url, 10, 90, 306, 207);
                              ctx.setFillStyle('#333333')
                              let name=that.data.itemName||that.data.spName;
                              that.wordsWrap(ctx,name,167,167, 10,110+217,12)
                             // ctx.fillText(name, 10,110+217);

                              // ctx.ellipse(44,22,300,200,0,0,Math.PI*2);
                                          ctx.fillStyle="#058";
                                          ctx.strokeStyle="#000";
                                         ctx.fill();
                                          ctx.stroke();
                                let tuanNum=that.data.grpQty
                               ctx.fillText('2人团', 10,100+257);
                               ctx.setFillStyle('#999')

                                ctx.fillText(`已团${tuanNum}件`, 60,100+257);
                                ctx.setFillStyle('#E4393C')
                                let price=that.data.grpAmount;
                                let aPrice=that.data.itemPrice;
                                ctx.fillText(`￥${price}`, 10,100+277);
                                 ctx.setFillStyle('#666666')
                                 ctx.fillText(`拼团省元${aPrice-price}`, 60,100+277);
                                  ctx.drawImage(that.codeImg, 286-10-89, 100+217, 89, 89);


                       ctx.draw()
                  //   }
                  // })

             // }
           // })

      //  ctx.draw(false,this.canvasToImage())


      },
      canvasToImage() {
              var that = this
              wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  width: 286,
                  height: 415,
                  destWidth: 286,
                  destHeight: 415,
                  canvasId: 'shareFrends',
                  success: function (res) {
                      console.log('朋友圈分享图生成成功:' + res.tempFilePath)
                      wx.saveFile({
                          tempFilePath: res.tempFilePath, // 当前显示图片的http链接
                          success:(data)=>{
                            console.log(data)
                            let savedFilePath=data.savedFilePath;
                            that.saveImageToPhotos(savedFilePath)
                          }
                         // urls: [res.tempFilePath] // 需要预览的图片http链接列表
                      })
                  },
                  fail: function (err) {
                      console.log('失败')
                      console.log(err)
                  }
              },this)
          },
          // 保存图片方法
          saveImage (filePath) {
            wx.saveImageToPhotosAlbum({
              filePath: filePath,  // 此为图片路径
              success: (res) => {
               wx.showToast({
                 title: `保存成功`,
                 icon: 'success',
                 duration: 2000
               })
              },
              fail: (err) => {
                wx.showToast({
                  title: `保存失败`,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          },
          // 点击保存图片到相册(授权)
          saveImageToPhotos (filePath) {
            let self = this
            // 相册授权
            wx.getSetting({
              success(res) {
                // 进行授权检测，未授权则进行弹层授权
                if (!res.authSetting['scope.writePhotosAlbum']) {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success () {
                      self.saveImage(filePath)
                    },
                    // 拒绝授权时，则进入手机设置页面，可进行授权设置
                    fail() {
                      wx.openSetting({
                        success: function (data) {
                          console.log("openSetting success");
                        },
                        fail: function (data) {
                          console.log("openSetting fail");
                        }
                      });
                    }
                  })
                } else {
                  // 已授权则直接进行保存图片
                  self.saveImage(filePath)
                }
              },
              fail(res) {
                console.log(res);
              }
            })
          },
        //文字换行处理
        // canvas 标题超出换行处理
        wordsWrap(ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
          let lineWidth = 0;
          let lastSubStrIndex = 0;
          for (let i = 0; i < name.length; i++) {
            lineWidth += ctx.measureText(name[i]).width;
            if (lineWidth > maxWidth) {
              ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY);
              srartY += wordsHight;
              lineWidth = 0;
              lastSubStrIndex = i;
            }
            if (i == name.length - 1) {
              ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY);
            }
          }
        },
  },

  created () {
    // let app = getApp()
  }
}
</script>

<style scoped>
.page{
  overflow: hidden;
  position: relative;
}
.sharecon{
  position:absolute;
  left: 1.5em;
  top: 1.5em;
  right: 1.5em;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
.sharebg{
  width: 100%;
  height: 100vh;
  display: block;
}
.sharecard{
  background: #fff;
  border-radius: 0.3em;
  padding: 0.8em;
  box-shadow: 0px 0px 10px #aaa;
  font-size: 0.8em;
  line-height: 0.9em;
}
.close{
  width: 1.4em;
  height: 1.4em;
  text-align: center;
  line-height: 1.4em;
  font-size: 1.6em;
  position: absolute;
  right: 0.4em;
  top: 0.4em;
  color: #666;
}
.share_user{
  line-height: 1.4em;
  margin-top: 1em;
}
.share_user img{
  width: 4em;
  height: 4em;
  border-radius: 50%;
  margin-right: 0.8em;
}
.share_goods{
  width: 100%;
  border-radius: 0.3em;
}
.share_store img{
  width: 7em;
  margin-left: 0.6em;
  margin-top: 0.8em;
}
.share_group span{
  background: #FF787E;
  display: inline-block;
  height: 1.4em;
  line-height: 1.4em;
  border-radius: 0.7em;
  padding: 0 0.4em;
  color: #fff;
}
.share_pirce{
  padding-top: 0.9em;
}
.share_pirce .red{
  font-size: 1.2em;
}
.share_title{
  margin-top: 0.8em;
  line-height: 1.4em;
  padding-bottom: 0.3em;
}
.share_tips{
  text-align: center;
  font-size: 0.9em;
  color: #FF787E;
  padding-top: 0.8em;
}
</style>
